﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace webapi.Helper
{
    public class NetHelper
    {
        private readonly HttpClient _httpClient;
        private string _clientId = "AcF3ckA65rSQQEEC7lMC3uubcONfSzaYvdeiVqOM9gZIhGRLjXP7hRRGGIJKU-0vNoJr5yMvTwmtOaR7";
        private string _clientSecret = "ELZsH37th3IH2NXRRpwWWtBFlOV3ODqv78kb24or6Ao4PhplRt98pFyDZps_-VmlltFm7nVv0S8J7o2n";

        public NetHelper()
        {
            _httpClient = new HttpClient(); ;
        }

        public string GetAccessTokenAsync()
        {
            var requestUri = "https://api-m.sandbox.paypal.com/v1/oauth2/token";
            var clientCredentials = $"{_clientId}:{_clientSecret}";
            var encodedClientCredentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(clientCredentials));

            var requestContent = new StringContent("grant_type=client_credentials", Encoding.UTF8, "application/x-www-form-urlencoded");
            using (var client = new HttpClient())
            {
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encodedClientCredentials);
                client.Timeout = TimeSpan.FromSeconds(3000);
                try
                {
                    var response = _httpClient.PostAsync(requestUri, requestContent).GetAwaiter().GetResult();
                    response.EnsureSuccessStatusCode();
                    string responseBody = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                    var obj = JsonConvert.DeserializeObject<AccessTokenOutput>(responseBody);
                    var token = obj.access_token;
                    return token;
                }
                catch (Exception ex)
                {
                    return "";
                }
            }
        }

        public string GetOrderStatus(string id, string token)
        {
            var requestUri = "https://api-m.sandbox.paypal.com/v2/checkout/orders/" + id;

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
                try
                {
                    HttpResponseMessage response = client.GetAsync(requestUri).GetAwaiter().GetResult(); ;
                    // 确保请求成功
                    response.EnsureSuccessStatusCode();

                    // 读取并打印响应内容
                    string responseBody = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                    var obj = JsonConvert.DeserializeObject<OrderInfoOutput>(responseBody);
                    return obj.status;
                }
                catch (Exception ex)
                {
                    return "";
                }
            }
        }
    }


    public class AccessTokenOutput
    {
        public string scope { get; set; }

        public string access_token { get; set; }

        public string token_type { get; set; }

        public string app_id { get; set; }

        public int expires_in { get; set; }

        public string nonce { get; set; }
    }

    public class OrderInfoOutput
    {
        public string status { get; set; }
    }
}
